﻿// // ******************************************************************
// //       /\ /|       @file       BaseAutoService.cs
// //       \ V/        @brief      await29
// //       | "")       @author     Await, 285283010@qq.com
// //       /  |
// //      /  \\        @Modified   2024-12-26 21:12
// //    *(__\_\        @Copyright  Copyright (c) , 2024-11-07 19:11 Await
// // ******************************************************************

using System.Globalization;
using Masa.BuildingBlocks.Data;
using Microsoft.Extensions.Options;

namespace AutomaticSubtitles.Service.Application.Base;

public class BaseAutoService
{
    private IEventBus EventBus     => GetRequiredService<IEventBus>();
    private IEventBus EventBusAuto => GetRequiredServiceAuto<IEventBus>();

    private IStringLocalizer<SharedResource> Localize => GetRequiredService<IStringLocalizer<SharedResource>>();

    protected async Task PublishAsync<TEvent>(TEvent @event, bool isAuto = false) where TEvent : IEvent
    {
        if (isAuto)
        {
            await EventBusAuto.PublishAsync(@event);
            return;
        }

        await EventBus.PublishAsync(@event);
    }

    protected TOptions? GetOptions<TOptions>() where TOptions : class
    {
        return GetService<IOptions<TOptions>>()?.Value;
    }

    /// <summary>
    ///     国际化语法返回
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    protected string ReturnMessage(string key)
    {
        return Localize[key]?.Value ?? "配置错误！";
    }

    /// <summary>
    /// 判断是否是否为空
    /// </summary>
    /// <param name="data"></param>
    /// <exception cref="ArgumentNullException"></exception>
    protected void IsDataNotExist(object? data)
    {
        if (data == null) throw new ArgumentNullException(ReturnMessage(NoExistent));
    }

    protected virtual IServiceProvider GetServiceProvider()
    {
        return MasaApp.GetService<IHttpContextAccessor>()?.HttpContext?.RequestServices ?? throw new MasaException("无法获取当前请求的ServiceProvider");
    }

    protected virtual IServiceProvider GetServiceProviderAuto()
    {
        return MasaApp.GetService<IServiceProvider>() ?? throw new MasaException("无法获取当前请求的ServiceProvider");
    }

    public TService? GetService<TService>()
    {
        return GetServiceProvider().GetService<TService>();
    }

    public TService GetRequiredService<TService>() where TService : notnull
    {
        return GetServiceProvider().GetRequiredService<TService>();
    }

    public TService GetRequiredServiceAuto<TService>() where TService : notnull
    {
        return GetServiceProviderAuto().GetRequiredService<TService>();
    }
}